package com.likou.second_challenge;

import java.util.*;

public class q56 {

    public int[][] merge(int[][] intervals) {

        List<int[]> ans = new ArrayList<>();
        int index = 0;

        Arrays.sort(intervals, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0] - o2[0];
            }
        });

        for (int[] interval : intervals) {
            if (!ans.isEmpty() && ans.get(index - 1)[1] >= interval[0]) {
                ans.get(index - 1)[1] = Math.max(ans.get(index - 1)[1], interval[1]);
            } else {
                ans.add(interval);
                index++;
            }
        }

        return ans.toArray(new int[ans.size()][2]);
    }

}
